package com.example.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.dao.DishesDao;
import com.example.dao.SetmealsDao;
import com.example.dao.SkusDao;
import com.example.dto.DishesDTO;
import com.example.dto.SetmealsDTO;
import com.example.dto.SkusDTO;
import com.example.dto.webchat.CategoriesWebchatQueryDTO;
import com.example.dto.webchat.CategoryGoodDTO;
import com.example.dto.webchat.GoodSkuDTO;
import com.example.entity.*;
import com.example.model.page.PageData;
import com.example.mybatis.service.impl.CrudServiceImpl;
import com.example.dao.ZyCategoriesDao;
import com.example.dto.ZyCategoriesDTO;
import com.example.security.SecurityUser;
import com.example.service.SkusService;
import com.example.service.SysStoreService;
import com.example.service.CategoriesService;
import com.example.utils.ConvertUtils;
import com.example.utils.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 分类表
 *
 * @author yyyyjinying 1020066395@qq.com
 * @since 1.0-SNAPSHOT 2025-04-27
 */
@Service
public class CategoriesServiceImpl extends CrudServiceImpl<ZyCategoriesDao, CategoriesEntity, ZyCategoriesDTO> implements CategoriesService {

    @Autowired
    private SysStoreService sysStoreService;

    @Autowired
    private DishesDao dishesDao;

    @Autowired
    private SetmealsDao  setmealsDao;

    @Autowired
    private SkusDao skusDao;
    @Override
    public List<ZyCategoriesDTO> categoriesGoodByStoreTenent(CategoriesWebchatQueryDTO categoriesWebchatQueryDTO){
        Long storeId = categoriesWebchatQueryDTO.getStoreId();
        Long tenantId = categoriesWebchatQueryDTO.getTenantId();

        // categoryId为null,查询所有分类id
        List<CategoriesEntity> categoriesEntities = baseDao.categoriesByStoreTenent(categoriesWebchatQueryDTO.getCategoryId(), storeId, tenantId);
        List<ZyCategoriesDTO> zyCategoriesDTOS = ConvertUtils.sourceToTarget(categoriesEntities, ZyCategoriesDTO.class);
        for (ZyCategoriesDTO zyCategoriesDTO : zyCategoriesDTOS) {
            List<CategoryGoodDTO> categoryGoodDTOS = new ArrayList<>();
            // 获取菜品
            List<DishesEntity> dishesByCategorieId = dishesDao.getDishesByCategorieId(zyCategoriesDTO.getId(), categoriesWebchatQueryDTO);
            List<CategoryGoodDTO> dishCategoryGoodDTOS = dishesByCategorieId.stream().map(item -> {
                CategoryGoodDTO categoryGoodDTO = new CategoryGoodDTO();
                categoryGoodDTO.setName(item.getName());
                categoryGoodDTO.setCategoryId(item.getCategoryId());
                categoryGoodDTO.setPrice(item.getPrice());
                categoryGoodDTO.setId(item.getDishId());
                categoryGoodDTO.setEatType(item.getEatType());
                categoryGoodDTO.setImageUrl(item.getImageUrl());
                categoryGoodDTO.setThumbnailUrl(item.getThumbnailUrl());
                categoryGoodDTO.setCategoryName(item.getCategoryName());
                categoryGoodDTO.setHasSku(item.getSkuCount() > 0);
                categoryGoodDTO.setIsSetmeal(false);

                // 获取商品规格
                if (categoryGoodDTO.getHasSku()) {
                    QueryWrapper<SkusEntity> skuQueryWrapper = new QueryWrapper<>();
                    skuQueryWrapper.eq("dish_id", item.getDishId());
                    List<SkusEntity> skusEntities = skusDao.selectList(skuQueryWrapper);
                    List<GoodSkuDTO> list = skusEntities.stream().map(skuItem -> {
                        GoodSkuDTO goodSkuDTO = ConvertUtils.sourceToTarget(skuItem, GoodSkuDTO.class);
                        goodSkuDTO.setGoodsId(categoryGoodDTO.getId());
                        goodSkuDTO.setGoodsName(categoryGoodDTO.getName());



                        return goodSkuDTO;
                    }).toList();
                    categoryGoodDTO.setSkuList(list);
                }
                return categoryGoodDTO;
            }).toList();

            if (!CollectionUtils.isEmpty(dishCategoryGoodDTOS)) {
                categoryGoodDTOS.addAll(dishCategoryGoodDTOS);
            }

            // 获取套餐
            QueryWrapper<SetmealsEntity> setmealsQueryWrapper = new QueryWrapper<>();
            setmealsQueryWrapper.eq("t1.category_id", zyCategoriesDTO.getId());
            setmealsQueryWrapper.apply("FIND_IN_SET({0}, t1.eat_type) > 0", categoriesWebchatQueryDTO.getEatType());
            List<SetmealsEntity> setmealsEntities = setmealsDao.selectList(setmealsQueryWrapper);
            List<CategoryGoodDTO> setmealCategoryGoodDTOS = setmealsEntities.stream().map(item -> {
                CategoryGoodDTO categoryGoodDTO = new CategoryGoodDTO();
                categoryGoodDTO.setName(item.getName());
                categoryGoodDTO.setCategoryId(item.getCategoryId());
                categoryGoodDTO.setPrice(item.getPrice());
                categoryGoodDTO.setId(item.getId());
                categoryGoodDTO.setEatType(item.getEatType());
                categoryGoodDTO.setImageUrl(item.getImageUrl());
                categoryGoodDTO.setThumbnailUrl(item.getThumbnailUrl());
                categoryGoodDTO.setCategoryName(item.getCategoryName());
                categoryGoodDTO.setIsSetmeal(true);
                return categoryGoodDTO;
            }).toList();

            if (!CollectionUtils.isEmpty(setmealCategoryGoodDTOS)) {
                categoryGoodDTOS.addAll(setmealCategoryGoodDTOS);
            }
            zyCategoriesDTO.setCategoryGoodList(categoryGoodDTOS);
        }

        List<ZyCategoriesDTO> list = zyCategoriesDTOS.stream().filter(item -> !CollectionUtils.isEmpty(item.getCategoryGoodList())).toList();
        return TreeUtils.build(list);
    }

    @Override
    public QueryWrapper<CategoriesEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<CategoriesEntity> wrapper = new QueryWrapper<>();

        String storeId = (String)params.get("storeId");
        wrapper.eq(StringUtils.isNotBlank(storeId), "store_id", storeId);

        return wrapper;
    }

    @Override
    public void save(ZyCategoriesDTO dto) {
        CategoriesEntity entity = ConvertUtils.sourceToTarget(dto, CategoriesEntity.class);
        entity.setId(snowflake.nextId()); // 主键id可能有错误
        SysStoreEntity sysStoreEntity = sysStoreService.selectById(entity.getStoreId());
        Long tenantId = sysStoreEntity.getTenantId();
        entity.setTenantId(tenantId);
        baseDao.insert(entity);
    }
    @Override
    public PageData<ZyCategoriesDTO> page(Map<String, Object> params) {
        IPage<CategoriesEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );
        List<CategoriesEntity> records = page.getRecords();
        List<ZyCategoriesDTO> zyCategoriesDTOS = ConvertUtils.sourceToTarget(records, ZyCategoriesDTO.class);
        List<ZyCategoriesDTO> build = TreeUtils.build(zyCategoriesDTOS);
        return getPageData(build, page.getTotal(), currentDtoClass());
    }



}